#!/bin/bash
# 每一周日 00：01 执行 
# crontab -e
# 01 * * * 0 /home/boc/work/bakmysql.sh
# filename:bakmysql.sh 

# set path 文件存储位置
bakpath='/home/boc/work/shell/'
logfile='/home/boc/work/shell/bak.log'
dbname='dbname'

themonth=${bakpath}`date +%y%m`'/'
theday=${themonth}`date +%d`'/' 
thetime=${theday}`date +%Y%m%d%H%M`'.'${dbname}'.sql.bak' 

declare -i month=`date +%y%m`
month=$month-1

echo '' >> $logfile
echo `date +%D\ %T` >> $logfile

for i in `ls -F $bakpath`; do
	if [[ -d $bakpath$i ]]; then
		if [[ $i < $month ]]; then
			echo 'delete out 2 month '$i >> $logfile
			rm -rf ${bakpath}$i
		else
			echo 'noting'
		fi
	fi
done

if [[ -d $themonth ]]; then
	echo $themonth 'is exist;' >> $logfile
else
	echo 'makedir ' $theday >> $logfile
	mkdir -p $theday
fi

if [[ -d $theday ]]; then
	echo $theday 'is exist;' >> $logfile
else
	echo 'makedir ' $theday >> $logfile
	mkdir $theday
fi

echo 'bakup mysqldatabase '${dbname}' - '${thetime} >> $logfile
touch $thetime

mysqldump -uroot -p123456 ${dbname} > $thetime 
